﻿using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class MenuController : Base
{
    private readonly ApplicationContext _applicationContext;
    private readonly MenuService _menuService;
    public MenuController(ApplicationContext applicationContext, MenuService menuService)
    {
        _applicationContext = applicationContext;
        _menuService = menuService;
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Menu_Index)]
    public async Task<IActionResult> IndexAsync()
    {
        var pagedList = await _menuService.GetCategorys();
        return Success(new { data = pagedList });
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Menu_Index)]
    public async Task<IActionResult> GetTree()
    {
        var allTree = await _menuService.GetCatTree();
        return Success(new { data = allTree });
    }

    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Menu_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        var data = await _menuService.GetInfo(id);
        IEnumerable<ViewMenu> catList = await _menuService.GetCateListAsync((int)MenuTypeEnum.Type.菜单);
        return Success(new { data, catList });
    }

    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Menu_AddOrEdit)]
    [Log(Name = "新增菜单")]
    public async Task<IActionResult> CreateAsync([FromBody] Menu menu)
    {
        var res = await _menuService.InsertAsync(menu);
        return Success("新增成功 ID:" + res.ToString());
    }

    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Menu_AddOrEdit)]
    [Log(Name = "修改菜单")]
    public async Task<IActionResult> EditAsync([FromBody] Menu menu)
    {
        Menu getMenu = await _menuService.GetInfo(menu.Id);
        getMenu.Pid = menu.Pid;
        getMenu.Name = menu.Name;
        getMenu.Type = menu.Type;
        getMenu.Sort = menu.Sort;
        getMenu.Status = menu.Status;
        getMenu.PathUrl = menu.PathUrl;
        getMenu.ComUrl = menu.ComUrl;
        getMenu.RoleCode = menu.RoleCode;
        getMenu.Icon = menu.Icon;
        getMenu.Redirect = menu.Redirect;
        getMenu.Hide = menu.Hide;
        await _menuService.UpdateAsync(getMenu);
        return Success($"修改菜单:{getMenu.Name} Id:{menu.Id}");
    }

    [HttpDelete, ActionName("Delete")]
    [ActionPermissionFilter(Permission = PermissionKeys.Menu_Delete)]
    [Log(Name = "删除菜单")]
    public async Task<IActionResult> DeleteAsync(int id)
    {
        if (await _menuService.DeleteAndDelCacheAsync(id) > 0)
            return Success("删除菜单,Id " + id);
        else
            return Fail("删除失败！");
    }

}
